from django.apps import AppConfig
import threading
import nacos
import time
import os
import sys


class DocServiceConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'doc_service'

    def send_heartbeat_continuously(self, client, service_name, ip, port, interval, retry_interval=15):
        while True:
            try:
                client.send_heartbeat(service_name, ip, port)
            except nacos.exception.NacosRequestException as e:
                print(f"连接异常，尝试重新连接: {str(e)}")
                # 等待一段时间后再次尝试连接
                time.sleep(retry_interval)
                try:
                    # 尝试重新注册服务并继续发送心跳
                    client.add_naming_instance(service_name, ip, port)
                except Exception as reconnection_error:
                    print(f"重新连接失败: {str(reconnection_error)}")
                    # 重新连接失败后再次等待，然后循环将继续尝试
                    time.sleep(retry_interval)
                    continue
            time.sleep(interval)

# nacos注册
    def ready(self) -> None:
        SERVICE_NAME = "report-doc-service"
        if os.environ.get("IS_DEBUG"):
            print("debug mode")
            return
        if 'runserver' in sys.argv:
            if not os.environ.get('NACOS_SERVER'):
                print("no nacos server")
                return
            server_address = os.environ.get('NACOS_SERVER')
            IP = os.environ.get('XU_HYBRID_IP', "127.0.0.1")
            PORT = int(os.environ.get('HOST_PORT', "8000"))

            HEARTBEAT_INTERVAL = 10  # 间隔时间，单位秒
            try:
                client = nacos.NacosClient(
                    server_addresses=server_address, namespace=os.environ.get('NACOS_NAMESPACE', "test-env"))
                client.add_naming_instance(SERVICE_NAME, IP, PORT)

                heartbeat_thread = threading.Thread(target=self.send_heartbeat_continuously, args=(
                    client, SERVICE_NAME, IP, PORT, HEARTBEAT_INTERVAL))
                heartbeat_thread.daemon = True  # 设置为守护线程
                heartbeat_thread.start()
            except:
                print(f"注册服务失败")
